'''
Created on Nov 11, 2010

@author: behrooz
'''
from django.core.management.base import BaseCommand
import datetime
from amscms.core.utils.twitter import post_to_twitter
from amscms import settings

class Command(BaseCommand):
    
    help = "Enables the recently registered ads whose publish start date is today"
    
    def handle(self, *args, **options):
        '''
        First find the ads that are registered but not enabled. The 
        start date should be today and the ad should not be enabled.
        '''
        from amscms.ams.models import Ad, AdOrder
        from django.utils import translation
        
        translation.activate(settings.LANGUAGE_CODE)
        
        now = datetime.datetime.now()
        recents = Ad.objects.exclude(enabled=True).filter(start_date__day=now.day, 
            start_date__month=now.month, start_date__year=now.year, end_date__gte=now)
        if recents is None or len(recents) == 0:
            return
        for ad in recents:
            if (not ad.enabled) and AdOrder.objects.is_paid(ad.id):
                ad.enabled = True
                ad.save()
                try:
                    # post to twitter
                    self.update_twitter(ad)
                except:
                    pass
                # email to the owner
                try: 
                        self.email_user(ad)
                except:
                    pass
    
    def update_twitter(self, ad):
        post_to_twitter(ad)
        return
    
    def email_user(self, ad):
        pass
        
